package com.spark.colliery.common.ext

import android.annotation.SuppressLint
import android.graphics.Color
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.ViewManager
import android.widget.EditText
import android.widget.ImageView
import com.jakewharton.rxbinding2.view.RxView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import io.reactivex.android.schedulers.AndroidSchedulers
import org.jetbrains.anko.custom.ankoView
import java.util.concurrent.TimeUnit

/**
 * View 隐藏或显示
 */
fun View.gone(yes: Boolean) {
    if (yes) {
        this.visibility = View.GONE
    } else {
        this.visibility = View.VISIBLE
    }
}

fun View.invisible(yes: Boolean) {
    if (yes) {
        this.visibility = View.INVISIBLE
    } else {
        this.visibility = View.VISIBLE
    }
}

/**
 * View 是否可见
 */
fun View.isVisible(): Boolean {
    return this.visibility == View.VISIBLE
}

/**
 * SwipeRefreshLayout 刷新时显示🌈的颜色
 */
fun SwipeRefreshLayout.colorful() {
    setColorSchemeColors(
            Color.parseColor("#FF0000"),
            Color.parseColor("#FF7F00"),
            Color.parseColor("#FFFF00"),
            Color.parseColor("#00FF00"),
            Color.parseColor("#00FFFF"),
            Color.parseColor("#0000FF"),
            Color.parseColor("#8B00FF")
    )
}


/**
 * 限制 EditText 的输入长度
 */
fun EditText.limitLength(len: Int) {
    val lengthFilter = InputFilter { source, start, end, dest, dstart, dend ->
        val sourceLen = source.toString().length
        val destLen = dest.toString().length
        if (sourceLen + destLen > len || sourceLen + destLen < 1)
            return@InputFilter ""
        return@InputFilter source
    }
    filters = arrayOf(lengthFilter)
}

/**
 * 显示或隐藏 EditText 输入的密码
 * 此处 EditText 的 inputType 应为 qr_password
 */
fun EditText.password(show: Boolean) {
    transformationMethod = if (show) {
        PasswordTransformationMethod.getInstance()
    } else {
        HideReturnsTransformationMethod.getInstance()
    }
    setSelection(length())
}

/**
 * EditText 和 clear 图标
 */
fun EditText.watchWithClear(ivClear: ImageView) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            ivClear.gone(s.isNullOrBlank())
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    })
    ivClear.setOnClickListener { setText("") }
}


/**
 * Recycler嵌套或者被嵌套在其他可滑动布局中，调整顺滑度
 */
fun RecyclerView.nestSmoothScoll(lm: RecyclerView.LayoutManager) {
    lm.isAutoMeasureEnabled = true
    this.setHasFixedSize(true)
    this.isNestedScrollingEnabled = false
    layoutManager = lm
}

/**
 * RecyclerView 自动加载更多
 * 缺点：无法监听 加载中、加载出错、没有更多了 等状态
 */
fun RecyclerView.autoLoadMoreV1(block: RecyclerView.() -> Unit) {
    addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
            val lm = layoutManager
            if (lm is LinearLayoutManager) {
                val totalItemCount = adapter.itemCount
                val lastVisibleItemPosition = lm.findLastVisibleItemPosition()
                val visibleItemCount = childCount
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition == totalItemCount - 1 && visibleItemCount > 0) {
                    block
                }
            }
        }
    })
}

/**
 * 老铁双击666💥💥💥
 */
@SuppressLint("CheckResult")
fun View.double(time: Long = 400, timeUnit: TimeUnit = TimeUnit.MILLISECONDS, onDoubleClickListener: OnDoubleClickListener?) {
    val origin = RxView.clicks(this).share()
    origin.buffer(origin.debounce(time, timeUnit)).observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    {
                        if (it.size >= 2)
                            onDoubleClickListener?.onDoubleClicked()
                    },
                    {
                        it.printStackTrace()
                    },
                    {

                    },
                    {

                    }
            )
}

interface OnDoubleClickListener {
    fun onDoubleClicked()
}

/**
 * <><><> Anko 自定义VIEW
 * */
/**
 * SmartRefreshLayout
 */
inline fun ViewManager.smartRefreshLayout(init: SmartRefreshLayout.() -> Unit): SmartRefreshLayout {
    return ankoView({
        SmartRefreshLayout(it)
    }, theme = 0, init = init)
}

inline fun ViewManager.smartRefreshLayout() = smartRefreshLayout {}